/**
 * Created by chengke on 2018/2/28.
 */

/**
 * Created by chengke on 2018/2/28.
 */

let FutuHttpClient = require('@futu/httpclient');
let FutuHttpRequest = FutuHttpClient.FutuHttpRequest;
let Adgroup = require('../models/Adgroup');
let Campaign = require('../models/Campaign');

module.exports = UnitService;

const BASE_API_URL = 'https://api.baidu.com/json/sms/service/AdgroupService/';
const API_GET_CAMPAIGN = 'getAdgroup';
const API_ADD_CAMPAIGN = 'addAdgroup';
const API_UPDATE_CAMPAIGN = 'updateAdgroup';
const API_DELETE_CAMPAIGN = 'deleteAdgroup';

const UNIT_ATTRS = [
    'adgroupId',
    'campaignId',
    'adgroupName',
    'maxPrice',
    'negativeWords',
    'exactNegativeWords',
    'pause',
    'status',
    'priceRatio',
    'pcPriceRatio',
    // 'accuPricePactor',
    // 'wordPricePactor',
    // 'widePricePactor',
    'matchPriceStatus',
];

/**
 * UnitService
 *
 * @constructor
 * @param {String} username 用户名
 * @param {String} password 密码
 * @param {String} token API 令牌
 * @param {Object} options 扩展参数
 */
function UnitService(username, password, token, options = {}) {
    this.username = username;
    this.password = password;
    this.token = token;
    this.options = options;
    this.commonHeader = {
        'username': this.username,
        'password': this.password,
        'token': this.token
    };
}

UnitService.prototype.getAdgroup = async function () {
    let plans = await Campaign.findAll({attributes: ['campaign_id']});
    let planIds = plans.map(function (plan) {
        return plan.dataValues.campaign_id;
    });
    let result = await this._requestSemAPI(BASE_API_URL + API_GET_CAMPAIGN, {
        'ids': planIds,
        'idType': 3,
        'adgroupFields': UNIT_ATTRS
    });
    console.log(JSON.stringify(result, null, 2));
    if (result.header && result.header.status === 0) {
        return result.body.data;
    } else {
        return '';
    }
};

UnitService.prototype.syncAdgroup = async function () {
    let adgroups = await this.getAdgroup();
    return adgroups.map(async function (item) {
        item.negativeWords = JSON.stringify(item.negativeWords);
        item.exactNegativeWords = JSON.stringify(item.exactNegativeWords);
        let adgroup = await Adgroup.findOne({
            where: {adgroup_id: item.adgroup_id}
        });
        let result;
        if (adgroup) {
            result = adgroup.update(item);
        } else {
            result = await Adgroup.create(item);
        }
        console.log(result);
    });
};

UnitService.prototype._requestSemAPI = async function (url, body) {
    let client = await FutuHttpClient.getInstanceByEndpoint();
    let request = new FutuHttpRequest(url, {}, {});
    request.setIsJson(true);
    request.setData({
        'header': this.commonHeader,
        'body': body
    });
    let response = await client.request('post', request);
    if (response.httpStatusCode !== 200) {
        throw new Error('request ' + url + 'failed: ' + response.message);
    }
    return JSON.parse(response.data || '{}');
};
